// 模拟数据
const statsData = {
    speciesCount: 128,
    weatherFactors: 5,
    coverageTime: 10,
    onlineUsers: 23,
    expertUsers: 12,
    expertPoints: 3,
    paperCount: 89,
    commentCount: 345
  };

  // 更新统计数据
  document.getElementById('speciesCount').textContent = statsData.speciesCount;
  document.getElementById('weatherFactors').textContent = statsData.weatherFactors;
  document.getElementById('coverageTime').textContent = statsData.coverageTime + '年';
  document.getElementById('onlineUsers').textContent = statsData.onlineUsers;
  document.getElementById('expertUsers').textContent = statsData.expertUsers;
  document.getElementById('expertPoints').textContent = statsData.expertPoints;
  document.getElementById('paperCount').textContent = statsData.paperCount;
  document.getElementById('commentCount').textContent = statsData.commentCount;

  // 初始化地图
  const map = L.map('map').setView([20, 0], 2);
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; OpenStreetMap contributors'
  }).addTo(map);

  // // 模拟物种位置数据
  // const speciesLocations = [
  //   { name: '猴子', lat: -3.4653, lon: -62.2159 },
  //   { name: '兔子', lat: 35.8617, lon: 104.1954 },
  //   { name: '大象', lat: -1.2921, lon: 36.8219 },
  //   { name: '老虎', lat: 20.5937, lon: 78.9629 },
  //   { name: '企鹅', lat: -75.2509, lon: -0.0714 }
  // ];
  // //从数据库里面调取物种数据
  

  // speciesLocations.forEach(species => {
  //   L.circleMarker([species.lat, species.lon], {
  //     radius: 8,
  //     fillColor: '#ff7800',
  //     color: '#fff',
  //     weight: 1,
  //     opacity: 1,
  //     fillOpacity: 0.8
  //   }).addTo(map).bindPopup(species.name);
  // });

  // 初始化 ECharts 图表
  const chart1 = echarts.init(document.getElementById('chart1'));
  const chart2 = echarts.init(document.getElementById('chart2'));

  // 图表1：物种轨迹数量分布
  const speciesData = [
    { name: '鸟类', value: 40 },
    { name: '哺乳动物', value: 30 },
    { name: '爬行类', value: 20 },
  ];

  const option1 = {
    title: {
      text: '物种轨迹数量分布',
      left: 'center',
      textStyle: { color: '#fff' }
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: 10,
      textStyle: { color: '#fff' }
    },
    series: [
      {
        name: '轨迹数量',
        type: 'pie',
        radius: '50%',
        data: speciesData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  chart1.setOption(option1);

  // 图表2：气象因子数据类型分布
  const weatherData = [
    { name: '温度', value: 48 },
    { name: '湿度', value: 48 },
    { name: '风速', value: 96 }
  ];

  const option2 = {
    title: {
      text: '气象因子数据类型分布',
      left: 'center',
      textStyle: { color: '#fff' }
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: weatherData.map(item => item.name),
      axisLabel: { color: '#fff' },
      axisLine: { lineStyle: { color: '#fff' } }
    },
    yAxis: {
      type: 'value',
      axisLabel: { color: '#fff' },
      axisLine: { lineStyle: { color: '#fff' } },
      splitLine: { lineStyle: { color: '#444' } }
    },
    series: [
      {
        data: weatherData.map(item => item.value),
        type: 'bar',
        itemStyle: {
          color: '#73C0DE'
        }
      }
    ]
  };

  chart2.setOption(option2);

  get_paper_num();
  get_comment_num();
  get_species_count();
  get_weather_factors();
  get_time_coverage();
  get_online_users();
  get_expert_users();
  get_species_points();
  async function get_paper_num() {
    try{
        const response = await fetch('http://localhost:4000/knowledge_git/getpapercount');
        const data = await response.json();
        console.log(data);
        document.getElementById('paperCount').textContent = data.data;
    } catch(error) {
        console.log(error);
    }

  }
  async function get_comment_num() {
    try{
        const response = await fetch('http://localhost:4000/knowledge_git/getcommentcount');
        const data = await response.json();
        console.log(data);
        document.getElementById('commentCount').textContent = data.data;
    } catch(error) {
        console.log(error);
    }

  }
  async function get_species_count() {
    try{
        const response = await fetch('http://localhost:4000/knowledge_git/get_track_count');
        const data = await response.json();
        console.log(data);
        document.getElementById('speciesCount').textContent = data.data;
    } catch(error) {
        console.log(error);
    }

  }
  async function get_weather_factors() {
    try{
        const response = await fetch('http://localhost:4000/knowledge_git/get_raster_count');
        const data = await response.json();
        console.log(data);
        document.getElementById('weatherFactors').textContent = data.data;
    } catch(error) {
        console.log(error);
    }

}
  async function get_time_coverage() {
    try{
        const response = await fetch('http://localhost:4000/knowledge_git/get_raster_time');
        const data = await response.json();
        console.log(data);
        document.getElementById('coverageTime').textContent = data.data + '年';
    } catch(error) {
        console.log(error);
    }

}
async function get_online_users() { 
    try{
        const response = await fetch('http://localhost:4000/knowledge_git/get_online_users');
        const data = await response.json();
        console.log(data);
        document.getElementById('onlineUsers').textContent = data.data;
    } catch(error) {
        console.log(error);
    }
  }

async function get_expert_users() { 
    try{
        const response = await fetch('http://localhost:4000/knowledge_git/get_expert_users');
        const data = await response.json();
        console.log(data);
        document.getElementById('expertUsers').textContent = data.data;
    } catch(error) {  
        console.log(error);
    }
  }

async function get_species_points() {
    try{
        const response = await fetch('http://localhost:4000/knowledge_git/get_track_points');
        const data = await response.json();
        console.log(data);
        //data中包含所有物种的坐标点
        //替换地图中的圆点坐标
        speciesLocations=data.data;
        const charts = {};

        // 修改弹出框内容，添加下拉菜单
        speciesLocations.forEach(species => {
          const marker = L.circleMarker([species.center[1], species.center[0]], {
            radius: 8,
            fillColor: '#ff7800',
            color: '#fff',
            weight: 1,
            opacity: 1,
            fillOpacity: 0.8
          }).addTo(map);

          // 添加带下拉菜单的弹出框
          var processedSpeciesName = species.species.replace(/\s+/g, '_');
          marker.bindPopup(`
          <div class="popup-content">
          <div style="display: flex; align-items: center;">
            <h3 style="margin-right: 10px;">${species.species}</h3>
            <select id="factorSelect-${processedSpeciesName}" class="factor-select"\
             style="width: 100px; height: 30px; padding: 5px; margin-left: 10px;">
              <option value="temperature" selected>温度</option>
              <option value="humidity">湿度</option>
              <option value="u_wind">风速(水平)</option>
              <option value="v_wind">风速(垂直)</option>
            </select>
          </div>
          <div style="margin-top: 10px; text-align: center;">
            <canvas id="lineChart-${processedSpeciesName}" width="400" height="200"></canvas>
          </div>
        </div>
          `);

        // 处理弹出框打开事件
        marker.on('popupopen', async function() {
          console.log('弹出框打开',species.species);
          processedSpeciesName = species.species.replace(/\s+/g, '_');
          
         // 确保元素存在
          const select = document.querySelector(`#factorSelect-${processedSpeciesName}`);
          
          // 如果元素不存在，等待一段时间后再尝试获取
          if (!select) {
            console.log('等待元素加载...');
            await new Promise(resolve => setTimeout(resolve, 100)); // 等待100毫秒
            const select = document.querySelector(`#factorSelect-${processedSpeciesName}`);
            if (!select) {
              console.error(`元素 #factorSelect-${processedSpeciesName} 仍不存在`);
              return;
            }
          }
          
          console.log('当前属性选择', select.value);
          await drawLineChart(species, select.value);
  
          
          // 绑定下拉菜单变更事件
          document.addEventListener('click', (e) => {
            if (e.target.classList.contains('factor-select')) {
              const factor = e.target.value;
              drawLineChart(species, factor);
            }
          });
          
        });

        // 清理图表实例当弹出框关闭时
        marker.on('popupclose', () => {
          if (charts[species.species]) {
            charts[species.species].destroy();
            delete charts[species.species];
          }
        });
      });

      // 修改后的绘图函数
      async function drawLineChart(species, factor = 'temperature') {
        try {
          var processedSpeciesName = species.species.replace(/\s+/g, '_');
          //确定物种的高度
          const height = species.category=='bird'?925:1000;
          console.log('该物种高度是',height);
          const response = await fetch(
            `http://localhost:4000/knowledge_git/get_raster_overlap/${species.species}/${height}/${factor}`
          );
          const data = await response.json();

          if (data.code !== 200 || !data.data || data.data.length === 0) {
            console.error('No data available for the chart');
            return;
          }

          // 处理数据
          // 处理数据
          const eventIds = data.data.map((item, index) => index + 1); // 从1开始的序列
          const rasterValues = data.data.map(item => item.raster_value);

          // 获取画布元素
          const canvas = document.querySelector(`#lineChart-${processedSpeciesName}`);
          const ctx = canvas.getContext('2d');

          // 销毁旧图表
          if (charts[species.species]) {
            charts[species.species].destroy();
          }

          let unit = '';
          if (factor === 'temperature') {
              unit = 'K';
          } else if (factor === 'humidity') {
              unit = '%';
          } else if (factor === 'u_wind' || factor === 'v_wind') {
              unit = 'm/s';
          }
          // 创建新图表
          charts[species.species] = new Chart(ctx, {
            type: 'line',
            data: {
              labels: eventIds,
              datasets: [{
                label: factor,
                data: rasterValues,
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                borderColor: 'rgba(75, 192, 192, 1)',
                borderWidth: 1,
                tension: 0.1
              }]
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,
              plugins: {
                legend: { position: 'top' },
                title: { display: true, text: `${factor}(${unit}) 变化趋势` }
              },
              scales: { y: { beginAtZero: false } }
            }
          });

        } catch (error) {
          console.error('Error fetching or rendering the chart:', error);
        }
      }
    } catch(error) {
        console.log(error);
    }
} 
